package com.sigmazero13.MKDummy.utils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;

import android.sax.Element;
import android.sax.EndElementListener;
import android.sax.EndTextElementListener;
import android.sax.RootElement;
import android.sax.StartElementListener;
import android.util.Xml;

import com.sigmazero13.MKDummy.models.ReferenceCard;
import com.sigmazero13.MKDummy.models.ReferenceCardSection;

public class ReferenceCardParser {
	
	// XML tags
	public static final String CARDS = "cards";
	public static final String CARD = "card";
	public static final String SECTION = "section";
	
	// XML attributes
	public static final String ID = "id";
	public static final String TITLE = "title";
	public static final String TYPE = "type";
	public static final String NAME = "name";
	
	private InputStream data;
	
	public ReferenceCardParser(InputStream data) {
		this.data = data;
	}
	
	public List<ReferenceCard> parse () {
		final ReferenceCard card = new ReferenceCard();
		final ReferenceCardSection section = new ReferenceCardSection();
		RootElement root = new RootElement(CARDS);
		final List<ReferenceCard> cards = new ArrayList<ReferenceCard>();
		Element item = root.getChild(CARD);
		
		item.setStartElementListener(new StartElementListener() {
			@Override
			public void start(Attributes attributes) {
				card.setId(attributes.getValue(ID));
				card.setTitle(attributes.getValue(TITLE));
				card.setType(attributes.getValue(TYPE));
			}
		});
		item.setEndElementListener(new EndElementListener() {
			@Override
			public void end() {
				cards.add(new ReferenceCard(card));
				card.clear();
			}
		});
		
		item.getChild(SECTION).setStartElementListener(new StartElementListener() {
			@Override
			public void start(Attributes attributes) {
				section.setTitle(attributes.getValue(NAME));
			}
		});
		item.getChild(SECTION).setEndTextElementListener(new EndTextElementListener() {
			@Override
			public void end(String body) {
				section.setText(body);
				card.addSection(new ReferenceCardSection(section));
			}
		});
		
		try {
			Xml.parse(data, Xml.Encoding.UTF_8, root.getContentHandler());
		} catch (Exception e) {
			return new ArrayList<ReferenceCard>();
		}
		
		return cards;
	}

}
